package com.lovely602.ai.alibaba.controller.audio;


import com.alibaba.cloud.ai.dashscope.api.DashScopeAudioTranscriptionApi;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeAudioTranscriptionOptions;
import com.alibaba.cloud.ai.dashscope.audio.transcription.AudioTranscriptionModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 语音转文本模型
 *
 * @author lizhixing
 */
@Slf4j
@RestController
@RequestMapping(value = "/ai/transcription")
public class AudioTranscriptionController {

    private static final String AUDIO_FILE_PATH = "E:\\audio";

    private static final String AUDIO_FILE_CONTENT = """
            床前明月光，
            疑是地上霜。
            举头望明月，
            低头思故乡。
            """;

    private static final String DEFAULT_MODEL = DashScopeAudioTranscriptionApi.AudioTranscriptionModel.PARAFORMER_REALTIME_V2.getValue();

    // 语音转文本
    private final AudioTranscriptionModel audioTranscriptionModel;

    public AudioTranscriptionController(AudioTranscriptionModel audioTranscriptionModel) {
        this.audioTranscriptionModel = audioTranscriptionModel;
    }


    /**
     * 语音转文本
     */
    @GetMapping(value = "/stt")
    public String stt() throws FileNotFoundException {

//        String currentDir = System.getProperty("user.dir");
//        Path filePath = Paths.get(currentDir, "hello_world_male_16k_16bit_mono.wav");
        Path filePath = Paths.get("E:\\audio\\output.mp3");

        Resource inputStreamResource = new FileSystemResource(filePath);

        DashScopeAudioTranscriptionOptions audioTranscriptionOptions = DashScopeAudioTranscriptionOptions
                .builder()
                .withModel(DEFAULT_MODEL)
                .build();

        AudioTranscriptionPrompt audioTranscriptionPrompt = new AudioTranscriptionPrompt(inputStreamResource, audioTranscriptionOptions);

        AudioTranscriptionResponse response = audioTranscriptionModel.call(audioTranscriptionPrompt);

        String result = "";

        if (Objects.nonNull(response) && Objects.nonNull(response.getResult())) {
            result = response.getResult().getOutput();
        }

        return result;
    }

}
